package xin.data
{
	import flash.events.NetStatusEvent;
	import flash.net.ObjectEncoding;
	import flash.net.SharedObject;
	import flash.net.SharedObjectFlushStatus;
	import flash.system.Security;
	import flash.system.SecurityPanel;

	/**
	 *  本地共享对象
	 * @author xin
	 */	
	public class XSharedObject
	{
		// 引用的共享对象
		private var _sharedObject:SharedObject;
		
		/**
		 * 当存储满了弹出"本地存储设置"面板时, 用户操作Flash本地存储时事件侦听
		 */		
		private function netStatus_sharedObject(evt:NetStatusEvent):void
		{
			this._sharedObject.removeEventListener(NetStatusEvent.NET_STATUS, netStatus_sharedObject);
			switch (evt.info.code)
			{
				// 同意扩展存储容量
				case "SharedObject.Flush.Success":
					// TODO GameUtils something.
					break;
				
				// 拒绝扩展存储容量
				case "SharedObject.Flush.Failed":
					// TODO GameUtils something.
					break;
			}
		}
		
		/**
		 * 构造函数
		 * @param name 本地共享对象的名称
		 */		
		public function XSharedObject(name:String)
		{
			this._sharedObject = SharedObject.getLocal(name);
			this._sharedObject.objectEncoding = ObjectEncoding.AMF3;
		}
		
		/**
		 * 设置数据
		 * <p>例子</p>
		 * <code>
		 * var _so:XSharedObject = new XSharedObject(name); <p/>
		 * _so.setValue(key, value);<p/>
		 * _so.flush();</code><p/>
		 * @param key 键
		 * @param value 值
		 */		
		public function setValue(key:String, value:*):void
		{
			if (value != null)
			{
				this._sharedObject.setProperty(key, value);
			}
			else
			{
				delete this._sharedObject.data[key];
			}
		}
		
		/**
		 * 获取数据
		 * @param key 键
		 */		
		public function getValue(key:String):Object
		{
			return this._sharedObject.data[key];
		}
		
		/**
		 * 保存数据到本地对象
		 */		
		public function flush():Boolean
		{
			var blSuccess:Boolean = true;
			
			try
			{
				var result:String = this._sharedObject.flush();
				if (result == SharedObjectFlushStatus.PENDING)
				{
					blSuccess = false;
					
					// 侦听当前用户的操作: 是否同意扩展Flash本地存储体积
					this._sharedObject.addEventListener(NetStatusEvent.NET_STATUS, netStatus_sharedObject);
				}
			}
			catch (e:Error)
			{
				blSuccess = false;
			}
			
			return blSuccess;
		}
		
		/**
		 * 清除该共享对象的所有数据
		 */		
		public function clear():void
		{
			this._sharedObject.clear();
		}
		
		/**
		 * 打开Flash"本地存储设置"
		 */		
		public function showSet():void
		{
			Security.showSettings(SecurityPanel.LOCAL_STORAGE);
		}
	}
}